import { queryOne, update, insetOrIgnore, executeSQLParam, queryAll } from '.';
import { isEmpty } from '../util/common';
import { getStorageUserId } from '../plus/store/UserData';


const saveOrUpdateChatSessionBatch  = (chatSessionList) => {
    return new Promise(async (resolve, reject) => {
        try{
            for(let i = 0; i < chatSessionList.length; i++){
                const sessionInfo = chatSessionList[i];
                sessionInfo.status = 1;
               
                let sessionData = await selectUserSessionByContactId(sessionInfo.contactId);
                console.log("sessionData", sessionData)
                if(!isEmpty(sessionData)){
                    await updateChatSession(sessionInfo)
                }else{
                    addChatSession(sessionInfo)
                }
            }
            resolve()
        }catch(error){
            reject()
        }
    })
}
//根据联系人id查询聊天会话
const selectUserSessionByContactId = (contactId) => {
    let sql = "select * from chat_session_user where user_id = ? and contact_id = ?";
    return queryOne(sql, [plus.storage.getItem("userId"), contactId])
}
//增加聊天会话
const addChatSession = (sessionInfo) => {
    sessionInfo.userId = plus.storage.getItem("userId");
    insetOrIgnore("chat_session_user", sessionInfo)
}

//更新聊天会话
const updateChatSession = (sessionInfo) => {
    const paramData = {
        userId: plus.storage.getItem("userId"),
        contactId: sessionInfo.contactId
    }
    const updateInfo = Object.assign({}, sessionInfo);
    updateInfo.userId = null;
    updateInfo.contactId = null;
    return update("chat_session_user", updateInfo, paramData)
}
//更新未读数
const updateNoreadCount = ({contactId, noReadCount}) => {
    let sql = "update chat_session_user set no_read_coun = no_read_coun + ? where user_id = ? and contact_id = ?";
    return executeSQLParam(sql, [noReadCount, plus.storage.getItem("userId"), contactId])
}

//查询会话
const selectUserSessionList = () => {
    let sql = "select * from chat_session_user where user_id = ? and status = 1";
    return queryAll(sql, [getStorageUserId()]);
}

//将已经读过的消息进行更改为0
const readClean = (contactId) => {
    let sql = "update chat_session_user set no_read_coun = 0 where user_id = ? and contact_id = ?"
    return executeSQLParam(sql, [getStorageUserId(), contactId])
}
//保存或更新会话
const saveOrUpdateSession = (currentSessionId, sessionInfo) => {
    return new Promise(async (resolve, _reject) => {
        let sessionData = await selectUserSessionByContactId(sessionInfo.contactId);
        if(sessionData){
            updateSessionMessage(currentSessionId, sessionInfo)
        } else {
            sessionInfo.noReadCount = 1;
            addChatSession(sessionInfo)
        }

        resolve()
    })
}
//发送消息时同步更新session
const updateSessionMessage = (currentSessionId, {
    sessionId,
    contactName,
    lastMessage,
    lastReceiveTime,
    contactId,
    memberCount
}) => {
    const params = [lastMessage, lastReceiveTime];
    let sql = "update chat_session_user set last_message = ?, last_receive_time=?, status = 1";
    if(!isEmpty(contactName)) {
        sql = sql + ", contact_name = ?"
        params.push(contactName)
    }
    if(!isEmpty(memberCount)){
        sql = sql + ", member_count = ?"
        params.push(memberCount)
    }
    if(sessionId !== currentSessionId){
        sql = sql + ", no_read_coun = no_read_coun + 1"
    }
    sql = sql + " where user_id = ? and contact_id = ?";
    params.push(getStorageUserId());
    params.push(contactId);
    return executeSQLParam(sql, params)
}

export {
    saveOrUpdateChatSessionBatch,
    updateNoreadCount,
    selectUserSessionList,
    readClean,
    updateSessionMessage,
    saveOrUpdateSession,
    selectUserSessionByContactId
}